<template>
  <el-dialog v-bind="$attrs" :visible.sync="visible" width="800px" destroy-on-close :close-on-click-modal="false" :close-on-press-escape="false">
    <div class="editor-dom">
      <div class="p1"><div v-for="code in startCode">{{ code }}</div></div>
      <div class="p2"ref="body"></div>
      <div class="p1"><div v-for="code in endCode">{{ code }}</div></div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="handleClose">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { basicSetup, EditorView } from 'codemirror'
import { oneDark } from '@codemirror/theme-one-dark'
import { javascript } from '@codemirror/lang-javascript'
export default {
  data() {
    return {
      endCode: [],
      startCode: [],
      editor: null,
      visible: false,
    };
  },
  methods: {
    async show(value = '', callback, doc) {
      if (doc) {
        this.startCode = doc.splice(0, doc.length - 2)
        this.endCode = doc.splice(doc.length - 2)
      }
      this.visible = true
      await this.$nextTick()
      this.editor = new EditorView({
        doc: value + '\n\n\n',
        parent: this.$refs.body,
        extensions: [basicSetup, javascript(), oneDark],
      })
      this.callback = callback
    },
    async handleClose() {
      try {
        await this.$confirm('确认关闭？')
        const code = this.editor.state.doc.text.join('\n')
        this.$emit('change', code)
        this.callback && this.callback(code)
        this.editor.destroy()
        this.visible = false
      } catch (error) {
        console.log(error)
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.editor-dom{
  font-size: 20px;
  background: #282c34;
  color: #7d8799;
  padding: 10px;
  .p2 {
    padding-left: 0;
  }
  .p1 div:last-child {
    color: #c678dd;
  }
}
</style>
<style>
.cm-editor {
  font-size: 20px;
}
.ͼ1 .cm-scroller {
  font-family: Consolas, 'Courier New', monospace !important;
}
</style>